# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

#queryset对象转换为json对象
from django.core import serializers
import json
# Create your views here.
import urllib
from .saltapi import salt, gen_jid
from .rqueue import rqueue
from .job_persist import jobPersist

def health(req):
    params = {
        'client': 'local',
        'fun': 'test.ping',
        'tgt': '*'
    }
    return JsonResponse(salt.postRequest(params))

def execute(req):
    isAsync = req.GET.get('async', True)

    params = {
        'fun': req.GET.get('fun', ''),
        'tgt': req.GET.get('tgt', '*'),
        'full_return': True,        
    }
    if req.GET.get('arg', '') != '':
        params['arg'] = req.GET['arg']
    
    if isAsync:
        return asyncExec(params)
    else:
        return syncExec(params)

def syncExec(params):
    jid = gen_jid()
    params['jid'] = jid
    params['client'] = 'local'
    result = salt.postRequest(params)
    result = {
        'jid': jid,
        'result': result
    }
    if 'arg' in params.keys():
        cmd = params['fun'] + ' ' + params['arg']
    else:
        cmd = params['fun']
    rqueue.enqueue(jobPersist, jid = jid, cmd = cmd, tgt = params['tgt'])    
    return JsonResponse(result)

def asyncExec(params):
    params['client'] = 'local_async'    
    jid = salt.postRequest(params)['return'][0]['jid']
    if 'arg' in params.keys():
        cmd = params['fun'] + ' ' + params['arg']
    else:
        cmd = params['fun']
    ## 调用后台任务
    rqueue.enqueue(jobPersist, jid = jid, cmd = cmd, tgt = params['tgt'])
    result = {
        'jid': jid
    }
    return JsonResponse(result)